import React, { useState, useRef, useEffect } from 'react';
import { Space, Table, Tag, Modal, Button, message } from 'antd';
import { AudioOutlined } from '@ant-design/icons';
import { Input } from 'antd';
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import Userfrom from '../../components/userfrom3/index'
import dayjs from 'dayjs'
import { getUsers, deleteUser, editUser, addUser } from "../../api/user";
export default function Anchormanmanagement() {
  const { Search } = Input;
  const [messageApi, contextHolder] = message.useMessage();
  const [size, setSize] = useState('large');
  const { confirm } = Modal
  const [userdata, setUser] = useState([])
  const [Searchdata, setSearch] = useState([])
  const [deletedata, setdeleteUser] = useState([])
  const [editdata, seteditUser] = useState([])
  const [editid, seteditUserID] = useState([])
  const [adddata, setaddUser] = useState([])
  const [dataSource, setdataSource] = useState([])
  const [isAddVisible, setisAddVisible] = useState(false)
  const [isUpdateVisible, setisUpdateVisible] = useState(false)
  const [roleList, setroleList] = useState([])
  const [regionList, setregionList] = useState([])
  const [current, setcurrent] = useState(null)
  const [isUpdateDisabled, setisUpdateDisabled] = useState(false)
  const AddForm = useRef(null)
  const UpdateForm = useRef(null)
  let index1 = ['冠心病', '气管炎', '支气管扩张', '肺炎'];
  let opertateFormLabel = [
    {
      model: "id",
      label: "id",
      type: "input_id",
    },
    {
      model: "nickName",
      label: "账号",
      type: "input",
    },
    {
      model: "School_of_Tourism1",
      label: "所属学院",
      type: "input",
    },
    {
      model: "title",
      label: "姓名",
      type: "input",
    },
    {
      model: "age",
      label: "学号",
      type: "input",
    },
    {
      model: "Live_direction1",
      label: "岗位",
      type: "select_Live_direction1",
    },
    {
      model: "age1",
      label: "性别",
      type: "age1_select",
    },
    {
      model: "company_list1",
      label: "就职公司",
      type: "input",
    },
    {
      model: "addr",
      label: "就职地址",
      type: "address",
    },
    {
      model: "birth2",
      label: "新增时间",
      type: "date",
    },
    {
      model: "birth3",
      label: "修改时间",
      type: "date",
    },
  ]
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '账号',
      dataIndex: 'nickName',
      key: 'nickName',
      render: (text) => <p>
        {text}
      </p>
      ,
      width: 100,
    },
    {
      title: '所属学院',
      dataIndex: 'School_of_Tourism1',
      key: 'School_of_Tourism1',
      render: (text) => <p>{text}</p>,
      width: 200,
    },
    {
      title: '学号',
      dataIndex: 'age',
      key: 'age',
    },
    {
      title: '姓名',
      dataIndex: 'title',
      key: 'title',
      render: (text) => <h3>{text}</h3>,
      width: 100,
    },
    {
      title: '性别',
      key: 'age1',
      dataIndex: 'age1',
      render: (sex) => {
        let colors = '';
        let sexs = '';
        if (sex === 1) {
          sexs = '男'
          colors = 'geekblue'
        } else if (sex === 2) {
          sexs = '女'
          colors = 'green'
        } else {
          sexs = '未知'
          colors = 'red'
        }
        return (
          <Tag color={colors}>
            {sexs}
          </Tag>
        );
      },
    },
    {
      title: '岗位',
      dataIndex: 'Live_direction1',
      key: 'Live_direction1',
      render: (sex) => {
        let colors = '';
        if (sex === "娱乐主播") {
          colors = 'geekblue'
        } else if (sex === "社交主播") {
          colors = 'green'
        } else if (sex === "教育主播") {
          colors = 'green'
        } else {
          colors = 'red'
        }
        return (
          <Tag color={colors}>
            {sex}
          </Tag>
        );
      },
    },
    {
      title: '修改时间',
      dataIndex: 'birth3',
      key: 'birth3',
      width: 120,
    },
    {
      title: "操作",
      render: (item) => {
        return <div>
          <Button danger icon={<DeleteOutlined />} onClick={() => confirmMethod(item)}>删除</Button>
          <Button type="primary" icon={<EditOutlined />} disabled={item.default} onClick={() => handleUpdate(item)} >修改</Button>
        </div>
      },
      width: 200,
    }
  ];
  const confirmMethod = (item) => {
    confirm({
      title: '你确定要删除?',
      icon: <ExclamationCircleOutlined />,
      onOk() {
        deleteMethod(item)
      },
      onCancel() {
      },
    });
  }
  const handleUpdate = (item) => {
    setisUpdateVisible(true)
    setTimeout(() => {
      const { birth, birth2, birth3, id } = item;
      item.birth = dayjs(birth);
      item.birth2 = dayjs(birth2);
      item.birth3 = dayjs(birth3);
      setregionList(opertateFormLabel);
      seteditUserID(id)
      UpdateForm.current.setFieldsValue(item);
    }, 100)
    setcurrent(item)
  }
  const handleChange = (item) => {
    setdataSource([...dataSource])
  }
  const getuserdatas = async () => {
    const result = await getUsers()
    const { users } = result.data;
    console.log(users);
    setUser(users)
  }
  useEffect(() => {
    getuserdatas()
  }, [])
  const deleteMethod = (item) => {
    const { id, role, patientindex } = item;
    deleteUser({ id }).then(res => {
      message.success("删除成功")
      getuserdatas()
    })
    var a = setdataSource(dataSource.filter(data => data.id !== item.id))
  }
  const handleAudit = (item) => {
  }
  const updateFormOK = () => {
    var a = UpdateForm.current.validateFields().then(value => {
      value.birth2 = value.birth2.format('YYYY-MM-DD');
      value.birth3 = value.birth3.format('YYYY-MM-DD');
      var b = userdata.map(v => v.title).indexOf(value.title);
      value.id = editid;
      editUser(value).then((response) => {
        getuserdatas()
        message.success('修改成功！')
      }).catch(e => {
        message.error('修改失败！')
      })
      setisUpdateVisible(false)
      setdataSource(dataSource.map(item => {
        if (item.id === current.id) {
          return {
            ...item,
            ...value,
            role: roleList.filter(data => data.id === value.roleId)[0]
          }
        }
        return item
      }))
      setisUpdateDisabled(!isUpdateDisabled)
    })
  }
  const addFormOK = () => {
    AddForm.current.validateFields().then(value => {
      const { birth, birth2, birth3 } = value;
      value.birth2 = birth2.format('YYYY-MM-DD');
      value.birth3 = birth3.format('YYYY-MM-DD');
      console.log(value);
      if (userdata.map(v => v.title).indexOf(value.title) != -1) {
        message.error("用户名已存在")
      } else {
        value.id = ++userdata.length
        setisAddVisible(false)
        AddForm.current.resetFields()
        addUser(value).then((response) => {
          message.success("添加成功!")
          getuserdatas()
        }).catch(e => {
          message.success("添加失败,请重试!")
        })
      }
    }).catch(err => {
      console.log(err)
    })
  }
  const suffix = (
    <AudioOutlined
      style={{
        fontSize: 16,
        color: '#1890ff',
      }}
    />
  );
  const onSearch = (value) => {
    let arr = [];
    setSearch(value)
    if (value) {
      arr = userdata.filter((data) => {
        return data.title.indexOf(value.toString()) !== -1;
      });
    } else {
      arr = userdata;
    }
    userdata.length = arr.length;
    setUser(arr)
    if (!value) {
      getuserdatas()
    }
  };
  const getdata = (value) => {
    if (!value.target.value) {
      getuserdatas()
    }
  }
  return (
    <div>
      <div className="spacewidth">
        <Button onClick={() => {
          setregionList(opertateFormLabel)
          setisAddVisible(true)
        }} type="primary" size={size}>新增</Button>
        <Search size="large" placeholder="请输入用户名" style={{ width: 200 }} onChange={getdata} onSearch={onSearch} enterButton />
      </div>
      <Table columns={columns} dataSource={userdata}
        pagination={{
          pageSize: 5
        }}
        rowKey={item => item.id} />
      <Modal
        open={isUpdateVisible}
        title="更新用户"
        okText="更新"
        cancelText="取消"
        onCancel={() => {
          setisUpdateVisible(false)
          setisUpdateDisabled(!isUpdateDisabled)
        }}
        onOk={() => updateFormOK()}>
        <Userfrom regionList={regionList} roleList={roleList} ref={UpdateForm} isUpdateDisabled={isUpdateDisabled} isUpdate={true}></Userfrom>
      </Modal>
      <Modal
        open={isAddVisible}
        title="添加用户"
        okText="确定"
        cancelText="取消"
        onCancel={() => {
          setisAddVisible(false)
        }}
        onOk={() => addFormOK()}>
        <Userfrom regionList={regionList} roleList={roleList} ref={AddForm}></Userfrom>
      </Modal>
    </div>
  )
}